package net.xuzhen97.distributed.transaction.course.common.configure;

import net.xuzhen97.distributed.transaction.course.common.Constant;
import net.xuzhen97.distributed.transaction.course.common.exception.CheckException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;
import java.util.Objects;

@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 自定义检查异常
     * @param e
     * @return
     */
    @ExceptionHandler(CheckException.class)
    @ResponseBody
    ResponseEntity<?> handleCheckException(CheckException e) {

        HttpStatus status = HttpStatus.CONFLICT;
        // 没有权限状态要符合http状态码
        if(Objects.equals(Constant.ERROR_NOT_PERMISSION, e.getCode())){
            status = HttpStatus.FORBIDDEN;
        }
        return ResponseEntity.status(status)
                .body(new ErrorResult(e.getCode(), e.getMessage()));
    }

    /**
     * Validated 验证异常
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    ResponseEntity<?> handleConstraintViolationException(ConstraintViolationException e){
        return ResponseEntity.status(HttpStatus.CONFLICT)
                .body(new ErrorResult(e.getMessage()));
    }

    /**
     * 默认异常处理, 超出范围的应该重点关注, 可以钉钉通知等多途径来解决问题
     * @param throwable
     * @return
     */
    @ExceptionHandler(Throwable.class)
    @ResponseBody
    ResponseEntity<?> defaultException(Throwable throwable){
        //TODO 应该重点关注
        throwable.printStackTrace();
        return ResponseEntity.status(HttpStatus.CONFLICT)
                .body(new ErrorResult(throwable.getMessage()));
    }
}

